<template>
  <div class="definitions-page app-page">
    <div class="page-header">
      <div class="header-left">
        <el-button class="back-btn" text circle @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <h2 class="app-section-title">参数定义</h2>
      </div>
      <div class="actions">
        <el-input v-model="keyword" placeholder="按名称/Key筛选" class="search-input" clearable />
        <el-button type="primary" :loading="loading" @click="loadDefinitions">查询</el-button>
        <el-button type="success" @click="openCreate">新建参数</el-button>
      </div>
    </div>

    <!-- 桌面端使用表格 -->
    <div class="desktop-only">
      <el-table :data="filteredData" v-loading="loading" border style="width: 100%" @row-dblclick="viewDetail">
        <el-table-column prop="paramKey" label="参数Key" min-width="200" />
        <el-table-column prop="paramName" label="参数名称" min-width="160" />
        <el-table-column prop="paramType" label="类型" width="100" />
        <el-table-column prop="currentValue" label="当前值" min-width="120" />
        <el-table-column prop="defaultValue" label="默认值" min-width="120" />
        <el-table-column prop="categoryName" label="分类" width="140" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" link @click="viewDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 移动端使用卡片列表 -->
    <div class="mobile-only">
      <el-skeleton :loading="loading" animated :count="4">
        <div v-for="item in filteredData" :key="item.id" class="def-card" @click="viewDetail(item)">
          <div class="def-row">
            <span class="def-key" :title="item.paramKey">{{ item.paramKey }}</span>
            <el-tag size="small" type="info">{{ item.paramType }}</el-tag>
          </div>
          <div class="def-name">{{ item.paramName }}</div>
          <div class="def-values">
            <span class="value">当前：{{ item.currentValue ?? '—' }}</span>
            <span class="value sub">默认：{{ item.defaultValue ?? '—' }}</span>
          </div>
          <div class="def-foot">
            <span class="category">{{ item.categoryName || '未分配' }}</span>
            <el-icon class="arrow"><ArrowRight /></el-icon>
          </div>
        </div>
      </el-skeleton>
    </div>

    <!-- 新建参数对话框 -->
    <el-dialog v-model="createVisible" title="新建参数" width="520px" :close-on-click-modal="false">
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="96px">
        <el-form-item label="参数Key" prop="paramKey">
          <el-input v-model.trim="createForm.paramKey" placeholder="仅字母/数字/.-_" @blur="onBlurCheckKey" />
        </el-form-item>
        <el-form-item label="参数名称" prop="paramName">
          <el-input v-model.trim="createForm.paramName" placeholder="如：数据库最大连接数" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="createForm.categoryId" placeholder="请选择分类" filterable style="width: 100%">
            <el-option v-for="c in categoryOptions" :key="c.id" :label="c.categoryName || c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-select v-model="createForm.dataType" placeholder="请选择类型" style="width: 100%">
            <el-option v-for="t in dataTypeOptions" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认值" prop="defaultValue">
          <template v-if="createForm.dataType === 'NUMBER'">
            <el-input-number v-model="defaultNumber" :step="1" style="width: 100%" />
          </template>
          <template v-else-if="createForm.dataType === 'BOOLEAN'">
            <el-switch v-model="defaultBoolean" />
          </template>
          <template v-else-if="createForm.dataType === 'JSON'">
            <el-input v-model="createForm.defaultValue" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder='例如：{"timeout":1000}' />
          </template>
          <template v-else>
            <el-input v-model="createForm.defaultValue" placeholder="可选" />
          </template>
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-switch v-model="requiredSwitch" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="createForm.description" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="用途、格式、依赖说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button type="primary" :loading="createLoading" @click="handleCreateSubmit">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getDefinitions, createDefinition, checkParamKey, getRealCategories } from '@/assets/api/mobile'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const data = ref([])
const keyword = ref('')

// 新建参数弹窗与表单
const createVisible = ref(false)
const createLoading = ref(false)
const createFormRef = ref()
const createForm = ref({
  paramKey: '',
  paramName: '',
  categoryId: undefined,
  dataType: 'STRING',
  defaultValue: '',
  valueRange: '',
  description: '',
  isRequired: 0,
  isSystem: 0,
  validationRule: '',
  tags: ''
})
const dataTypeOptions = ['STRING', 'NUMBER', 'BOOLEAN', 'JSON']
const categoryOptions = ref([])
const defaultNumber = ref(0)
const defaultBoolean = ref(false)
const requiredSwitch = computed({
  get: () => createForm.value.isRequired === 1,
  set: (v) => { createForm.value.isRequired = v ? 1 : 0 }
})

const createRules = {
  paramKey: [
    { required: true, message: '请输入参数Key', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9._-]+$/, message: '仅支持字母/数字/点/中划线/下划线', trigger: 'blur' },
    { validator: async (_r, v, cb) => {
        if (!v) return cb()
        try {
          const res = await checkParamKey({ paramKey: v })
          const exists = res?.data?.data === true || res?.data === true
          if (exists) return cb(new Error('参数Key已存在'))
          cb()
        } catch (e) {
          cb()
        }
      }, trigger: 'blur' }
  ],
  paramName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  dataType: [{ required: true, message: '请选择类型', trigger: 'change' }],
  defaultValue: [{ validator: (_r, v, cb) => {
      const t = createForm.value.dataType
      if (t === 'NUMBER') {
        if (v === '' || v === null || v === undefined) return cb()
        return isNaN(Number(v)) ? cb(new Error('必须是数字')) : cb()
      }
      if (t === 'JSON') {
        if (!v) return cb()
        try { JSON.parse(v); cb() } catch (_e) { cb(new Error('JSON格式不正确')) }
        return
      }
      cb()
    }, trigger: 'blur' }]
}

const normalizeList = (res) => {
  if (Array.isArray(res)) return res
  if (Array.isArray(res?.data?.data)) return res.data.data
  if (Array.isArray(res?.data)) return res.data
  return []
}

const loadDefinitions = async () => {
  loading.value = true
  try {
    const categoryId = route.query.categoryId
    const res = await getDefinitions(categoryId ? { categoryId } : undefined)
    data.value = normalizeList(res)
  } catch (e) {
    ElMessage.error('获取参数定义失败')
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    const res = await getRealCategories()
    const list = Array.isArray(res?.data?.data) ? res.data.data : (Array.isArray(res?.data) ? res.data : [])
    categoryOptions.value = list
  } catch (_e) {
    categoryOptions.value = []
  }
}

const filteredData = computed(() => {
  if (!keyword.value) return data.value
  const k = keyword.value.toLowerCase()
  return data.value.filter(it =>
    String(it.paramKey || '').toLowerCase().includes(k) ||
    String(it.paramName || '').toLowerCase().includes(k)
  )
})

const viewDetail = (row) => {
  if (!row?.id) return
  router.push(`/param-engine/definitions/${row.id}`)
}

const goBack = () => {
  // 如果来自特定分类，返回分类页面
  if (route.query.categoryId) {
    router.push('/param-engine/categories')
  } else {
    // 否则返回参数引擎首页（仪表盘）
    router.push('/param-engine/dashboard')
  }
}

const openCreate = async () => {
  if (categoryOptions.value.length === 0) await loadCategories()
  // 预填分类
  const cid = route.query.categoryId
  createForm.value = {
    paramKey: '',
    paramName: '',
    categoryId: cid ? Number(cid) : undefined,
    dataType: 'STRING',
    defaultValue: '',
    valueRange: '',
    description: '',
    isRequired: 0,
    isSystem: 0,
    validationRule: '',
    tags: ''
  }
  defaultNumber.value = 0
  defaultBoolean.value = false
  createVisible.value = true
}

const onBlurCheckKey = async () => {
  const v = createForm.value.paramKey
  if (!v) return
  try {
    const res = await checkParamKey({ paramKey: v })
    const exists = res?.data?.data === true || res?.data === true
    if (exists) ElMessage.warning('参数Key已存在')
  } catch (_e) {}
}

const handleCreateSubmit = () => {
  // 同步默认值转换
  if (createForm.value.dataType === 'NUMBER') {
    createForm.value.defaultValue = (defaultNumber.value ?? 0) + ''
  } else if (createForm.value.dataType === 'BOOLEAN') {
    createForm.value.defaultValue = defaultBoolean.value ? 'true' : 'false'
  }

  createFormRef.value?.validate(async (ok) => {
    if (!ok) return
    createLoading.value = true
    try {
      const payload = { ...createForm.value }
      // 删除空字符串字段，避免触发后端数据完整性校验
      ;['valueRange','validationRule','tags','defaultValue','description'].forEach(k => {
        if (payload[k] === '') delete payload[k]
      })
      const res = await createDefinition(payload)
      const success = res?.data?.code === 200 || res?.code === 200 || res?.data === true
      if (success) {
        ElMessage.success('创建成功')
        createVisible.value = false
        await loadDefinitions()
      } else {
        ElMessage.error(res?.data?.msg || '创建失败')
      }
    } catch (e) {
      const msg = e?.response?.data?.message || e?.message || '创建失败'
      ElMessage.error(msg)
    } finally {
      createLoading.value = false
    }
  })
}

watch(() => route.query.categoryId, loadDefinitions)
onMounted(() => { loadDefinitions() })
</script>

<style scoped>
.definitions-page { position: relative; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.header-left { display: flex; align-items: center; gap: 8px; }
.search-input { width: 240px; margin-right: 8px; }
.back-btn { padding: 6px; }

/* 桌面端可见 */
.desktop-only { display: block; }
/* 移动端隐藏 */
.mobile-only { display: none; }

/* 移动端卡片样式 */
.def-card {
  background: white;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  margin-bottom: 12px;
}
.def-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; }
.def-key { font-weight: 600; font-size: 14px; color: #262626; max-width: 70%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.def-name { color: var(--app-subtext); font-size: 13px; margin-bottom: 6px; }
.def-values { display: flex; gap: 12px; font-size: 12px; color: #595959; }
.def-values .sub { color: #8c8c8c; }
.def-foot { display: flex; align-items: center; justify-content: space-between; margin-top: 8px; font-size: 12px; color: #8c8c8c; }
.def-foot .arrow { color: #bfbfbf; }

@media (max-width: 768px) {
  .desktop-only { display: none; }
  .mobile-only { display: block; }
  .search-input { width: 160px; }
}
</style>






